<?

	class Config {
		
		private $cfgdir = 'etc/';
		private $file;
		private $config;
				
		public function __get($name) {
			// need comments? o_O
			return $this->config[$name];
		}
				
		public function __set($n, $v) {
			// need comments? o_O
			if ($this->protected) Log::fatal("Error: trying to write protected config!");
			$this->config[$n] = $v;
			return $v;
		}
		
		public function __construct($name) {
			
			if (isset($GLOBALS['cfgdir'])) 
			{
				// local default value of cfgdir must be owerwriten by it's global equivalent  
				$this->cfgdir = $GLOBALS['cfgdir'];
			}
			
			// Installation mode hack!!!
			if ($name = 'libdb') 
			{
				$this->cfgdir = 'inc/setup/';
			}
			
			$name = escapeshellcmd(strtolower($name));
			$this->file = $this->cfgdir.$name.'.php';
			if (file_exists($this->file)) {
				$data = file_get_contents($this->file);
				$arr = unserialize($data);
				// please: don't forget to deny acces to config directory from web!
				if (!is_array($arr)) {
					// config file contains Cercea Wade configuration 
					eval ('?>'.$data.'<?');
				} else {
					// config file contains packed by serialize() array
					$this->config = $arr;
				}
			}
		}
		
		public function save() {
			// TODO: must throw XMLExecption
			// TODO: must check config file modification time 
			$arr = $this->config;
			$ret = serialize($arr);
			file_put_contents($this->file, $ret);
			if (!file_exists($this->file)) {
				throw new XMLException(QConst::X_CONFIG_NOT_WRITABLE, 'can\'t write to "'.$this->file.'". please, exec in shell command `chmod o+xw '.$_SERVER['DOCUMENT_ROOT'].'.'.dirname($_SERVER['PHP_SELF']).'/'.$GLOBALS['cfgdir'].'`');
			}
			$hta = "ORDER ALLOW, DENY\r\nDENY FROM ALL";
			file_put_contents($this->cfgdir.'.htaccess', $hta);
		}

		private function  r_print ($a) {
			// TODO: remove this shit or move to another lib
			$ret = "array(\n";
			foreach ($a as $key=>$val) {
				if ($val) {
					if (is_array($val)) $ret .= "\tstripslashes('".addslashes($key)."') => ".r_print($val).", \n";
					else $ret .= "\tstripslashes('".addslashes($key)."')=>stripslashes('".addslashes($val)."'),\n";
				}
			}
			$ret .= ")"; 
			return $ret;
		}
		
		function src() {
			return $this->config;
		}
		
	}